package cn.bouncyslime.algorithms.stack.balanceSymbol;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

/**
 * 40:(
 * 41:)
 * 91:[
 * 93:]
 * 123:{
 * 125:}
 * 平衡符号，判断开放符号是否有对应的封闭符号，并且符号的顺序是否是正确的
 * @author 张一卓
 */
public class BalanceSymbol {
	public static void main(String[] args) {
		Deque<Character> stack = new LinkedList<>();
		List<Character> charList = new ArrayList<>();
		List<Character> openSymbolList = new ArrayList<>();
		List<Character> closedSymbolList = new ArrayList<>();
		openSymbolList.add('(');
		openSymbolList.add('[');
		openSymbolList.add('{');
		closedSymbolList.add(')');
		closedSymbolList.add(']');
		closedSymbolList.add('}');
		try {
			BufferedReader bufferedReader = new BufferedReader(new FileReader("stack_BalanceSymbol2.txt"));
			int aChar;
			while((aChar=bufferedReader.read())!=-1) {
				charList.add((char)aChar);
			}
			Iterator<Character> iterator = charList.iterator();
			while(iterator.hasNext()) {
				char achar = iterator.next();
				if(stack.isEmpty() && closedSymbolList.contains(achar)) {
					System.out.println("出错，没有开放符号");
					return;
				}else if(openSymbolList.contains(achar)) {
					stack.push(achar);
				}else if(closedSymbolList.contains(achar)) {
					char bchar = stack.pop();
					if (openSymbolList.indexOf(bchar) != closedSymbolList.indexOf(achar)) {
						System.out.println("报错，开放符号与封闭符号不对应");
						return;
					}
				}
			}
			if(!stack.isEmpty()) {
				System.out.println("出错，没有封闭符号");
				return;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
